#ifndef SAFE_VECTOR_H
#define SAFE_VECTOR_H
#include <vector>

//#include <safe_error.h>

void bounds_error();
void iterator_error();

namespace safe_stl
{
template<class T>
class vector: public std::vector<T>
{
public:
    T& operator[](unsigned int index)
    {
        if(index >= std::vector<T>::size())
           bounds_error();
        return std::vector<T>::operator[](index);
    }
    const T& operator[](unsigned int index) const
    {
        if(index >= std::vector<T>::size())
           bounds_error();
        return std::vector<T>::operator[](index);
    }

    class vector_iterator
    {
       vector<T>* _owner;
       unsigned int _index;
    public:
       typedef T ElemType;

       vector_iterator(vector<T>* owner,unsigned int index)
       {
           _index = index;
           _owner = owner;
       }
       
       /*T operator * ()
       {
            if(_index >= _owner->size())
              bounds_error();
            return _owner->operator[](_index);
       }*/

       T& operator * ()
       {
            if(_index >= _owner->size())
              bounds_error();
            return _owner->operator[](_index);
       }

       vector_iterator operator++()
       {
          _index++;
          return *this;
       }

       vector_iterator operator--()
       {
          if(_index > 0)
            bounds_error();
          return *this; 
       }

       vector_iterator operator++(int dummy)
       {
          vector_iterator copy= *this;
          _index++;
          return copy;
       }

       vector_iterator operator--(int dummy)
       {
          if(_index == 0)
            bounds_error();
          vector_iterator copy= *this;
          _index--;
          return copy;
       }

       bool operator == (vector_iterator other)
       {
           if(_owner != other._owner)
              iterator_error();
           if(_index >=  _owner->size() && other._index  >= other._owner->size())
             return true;
           if(_index == other._index)
             return true;
       }

       bool operator != (vector_iterator other)
       {
          return !(*this == other);
       }

       vector_iterator operator +(unsigned int nElements)
       {
           vector_iterator i2 = *this;
           i2._index += nElements;
           if(i2._index >= i2._owner->size())
              bounds_error();
           return i2;
       } 
       unsigned int operator -(vector_iterator i2)
       {
          if(_index < i2._index)
           bounds_error();
          return _index - i2._index;          
       }       
    };
    typedef vector_iterator iterator;

    iterator begin()
    {
       vector_iterator vi (this,0);
       return vi;
    }

    iterator end()
    {
       vector_iterator vi (this,std::vector<T>::size());
       return vi;
    }
};

}

#endif
